<template>
  <view class="tabpane">
    <view v-if="$slots.default" class="tabpane__content" :style="[getContentStyle]">
      <slot v-if="rendered"></slot>
    </view>
  </view>
</template>

<script lang="ts">
import {
  defineComponent,
  inject,
  onMounted,
  reactive,
  toRefs,
  onUnmounted,
  watch,
  computed,
} from '@vue/composition-api'

export default defineComponent({
  props: {
    title: {
      type: [String, Number],
      default: '',
    },
    paneKey: {
      type: [String, Number],
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    padding: {
      type: String,
      default: '48rpx 40rpx',
    },
    background: {
      type: String,
      default: '#fff',
    },
    height: {
      type: String,
      default: '',
    },
  },
  options: {
    virtualHost: true, //  将自定义节点设置成虚拟的，更加接近Vue组件的表现。我们不希望自定义组件的这个节点本身可以设置样式、响应 flex 布局等，而是希望自定义组件内部的第一层节点能够响应 flex 布局或者样式由自定义组件本身完全决定
  },
  setup(props) {
    const tabsParent: any = inject('tabsParent', null)
    const state = reactive({
      rendered: !tabsParent.lazyRender,
    })
    const getContentStyle = computed(() => {
      return {
        padding: props.padding,
        height: props.height,
        background: props.background,
      }
    })
    const setRender = (paneKey, pValue) => {
      if (!tabsParent.lazyRender || state.rendered) {
        return
      }

      state.rendered = paneKey === pValue
    }
    let paneKey

    watch(
      () => props.title,
      (newTitle) => {
        if (tabsParent && tabsParent.setTitle) {
          tabsParent.setTitle(paneKey, newTitle)
        }
      }
    )

    onMounted(async () => {
      if (tabsParent && tabsParent.addTab) {
        paneKey = props.paneKey !== null ? props.paneKey : tabsParent.tabs.length

        tabsParent.addTab({
          title: props.title,
          disabled: props.disabled,
          paneKey,
          vm: {
            setRender,
          },
        })
      }
    })

    onUnmounted(async () => {
      if (tabsParent && tabsParent.remoeTab) {
        tabsParent.removeTab(paneKey)
      }
    })

    return { ...toRefs(state), getContentStyle }
  },
})
</script>

<style lang="scss" scoped>
.tabpane {
  overflow: auto;
  width: 100%;
  flex-shrink: 0;
  display: block;
  overflow: auto;
  &__content {
    padding: 48rpx 40rpx;
  }
}
</style>
